<template>
  <view class="video-preview-container">
    <!-- 设备名称栏 -->
    <view class="device-bar">
      <text class="device-label">E094154520002</text>
    </view>

    <!-- 视频播放区域 -->
    <view class="video-section">
      <video :src="liveUrl" :autoplay="true" class="video-player" :is-live="true" @error="onVideoError" :enableNative="true"></video>
    </view>

    <!-- 功能按钮区域 -->
    <!-- <view class="function-buttons">
      <view class="function-btn" @click="showInfo">
        <image :src="infoSrc" class="btn-icon-img"></image>
        <text class="btn-label">信息</text>
      </view>

      <view class="function-btn" @click="refreshVideo">
        <image :src="refreshSrc" class="btn-icon-img"></image>
        <text class="btn-label">刷新</text>
      </view>
      <view class="function-btn" @click="takeSnapshot">
        <image :src="snapshotSrc" class="btn-icon-img"></image>
        <text class="btn-label">截图</text>
      </view>
    </view> -->

    <!-- 回放时间选择区域 -->
    <view class="time-select-section">
      <!-- <view class="time-select-item" @click="openStartTimePicker">
        <view class="time-label">开始时间</view>
        <view class="time-value-wrapper">
          <view class="time-value">{{ startTime }}</view>
          <text class="time-arrow">›</text>
        </view>
      </view>
      <view class="time-select-item" @click="openEndTimePicker">
        <view class="time-label">结束时间</view>
        <view class="time-value-wrapper">
          <view class="time-value">{{ endTime }}</view>
          <text class="time-arrow">›</text>
        </view>
      </view> -->
      <view class="time-select-item" @click="handleDateSelect">
        <view class="time-label">选择时间</view>
        <view class="time-value-wrapper">
          <view class="time-value">{{ date }} {{ startTime }} - {{ endTime }}</view>
          <text class="time-arrow">›</text>
        </view>
      </view>
    </view>

    <!-- 开始时间选择器 -->
    <!-- <u-datetime-picker
      :show="showStartPicker"
      v-model="startTimeStamp"
      mode="datetime"
      @confirm="onStartTimeConfirm"
      @cancel="showStartPicker = false"
    ></u-datetime-picker> -->

    <!-- 结束时间选择器 -->
    <!-- <u-datetime-picker
      :show="showEndPicker"
      v-model="endTimeStamp"
      mode="datetime"
      @confirm="onEndTimeConfirm"
      @cancel="showEndPicker = false"
    ></u-datetime-picker> -->

    <u-popup :show="show" @open="show = true">
      <view class="time_top_box">
        <view class="time_close" @click="close">取消</view>
        <view class="time_text">{{ title }}</view>
        <view class="time_comfirm" @click="confirmDate">确认</view>
      </view>
      <uni-calendar :date="dateCheckedValue" :insert="true" @change="changeDate" />
      <view class="time-select-section">
        <view class="time-select-item" @click="openTimeSlot">
          <view class="time-label">选择时间段</view>
          <view class="time-value-wrapper">
            <view class="time-value">{{ startTimeCheckedValue }} - {{ endTimeCheckedValue }}</view>
            <text class="time-arrow">›</text>
          </view>
        </view>
      </view>
    </u-popup>

    <timeSlot
      ref="timeslot"
      @confirm="confirmTime"
      @close="show = true"
      :defaultStartValue="{ hour: startTimeCheckedValue.split(':')[0], min: startTimeCheckedValue.split(':')[1] }"
      :defaultEndValue="{ hour: endTimeCheckedValue.split(':')[0], min: endTimeCheckedValue.split(':')[1] }"
    ></timeSlot>
  </view>
</template>

<script>
import timeSlot from "./components/wanghexu-timeslot/wanghexu-timeslot.vue"
import { userPlay, snap, gimbalDirectionControl, getStart, getM3u8Url } from "@/apis/equipment"
import dayjs from "dayjs"

export default {
  components: {
    timeSlot,
  },
  data() {
    return {
      infoSrc: require("@/static/images/信息.png"),
      refreshSrc: require("@/static/images/刷新.png"),
      snapshotSrc: require("@/static/images/截图.png"),
      directionSrc: require("@/static/images/方向.png"),
      zoomSrc: require("@/static/images/变焦.png"),
      deviceName: "金秋巷",
      deviceCode: "P085.0 T035.1 X1.0",
      currentTime: "2025-10-22 13:17:22",
      videoUrl: "", // 原生video地址
      liveUrl: "", // 钉钉直播地址

      timer: null,
      channelId: "",
      deviceId: "",
      // 云台控制相关
      showGimbalControl: false,
      controlType: "direction", // direction | zoom
      directionTimer: null,
      zoomTimer: null,
      apertureTimer: null,
      stream: "",
      date: dayjs().format("YYYY-MM-DD"),
      startTime: dayjs().subtract(2, "minute").format("HH:mm"),
      endTime: dayjs().format("HH:mm"),
      startTimeStamp: dayjs().subtract(2, "minute").valueOf(),
      endTimeStamp: dayjs().valueOf(),

      dateCheckedValue: dayjs().format("YYYY-MM-DD"),
      startTimeCheckedValue: dayjs().subtract(2, "minute").format("HH:mm"),
      endTimeCheckedValue: dayjs().format("HH:mm"),

      showStartPicker: false,
      showEndPicker: false,
      timer: null,
      show: false,
    }
  },
  methods: {
    // 获取视频
    fetchUserPlay() {
      const params = {
        channelId: this.channelId,
        startTime: this.date + " " + this.startTime + ":00",
        endTime: this.date + " " + this.endTime + ":00",
      }
      console.log("params :>> ", params)
      getStart(params).then((res) => {
        this.fetchGetM3u8Url(res.sessionId)
      })
    },
    fetchGetM3u8Url(sessionId) {
      let req = { sessionId }
      getM3u8Url(req).then((res) => {
        // 如果code为wait，则循序调用getM3u8Url, 直到code为success
        if (res.code === "wait") {
          this.timer = setTimeout(() => {
            this.fetchGetM3u8Url(res.sessionId)
          }, 1000)
        } else {
          clearTimeout(this.timer)
          this.liveUrl = "http://58.16.58.85:18080" + res.m3u8Url
        }
      })
    },
    getChannelInfo() {
      const params = { id: this.channelId }
      getChannelInfo(params).then((res) => {
        console.log("res :>> ", res)
      })
    },

    // 原生video错误
    onVideoError(e) {
      console.error("视频错误:", e)
    },

    // 显示信息
    showInfo() {
      uni.showModal({
        title: "设备信息",
        content: `设备名称: ${this.deviceName}\n设备编号: ${this.deviceCode}\n当前时间: ${this.currentTime}`,
        showCancel: false,
      })
    },
    handleDateSelect() {
      this.show = true
      this.dateCheckedValue = this.date
      this.startTimeCheckedValue = this.startTime
      this.endTimeCheckedValue = this.endTime
    },

    // 打开开始时间选择器
    openStartTimePicker() {
      console.log("this.$refs.timeslot :>> ", this.$refs.timeslot)

      this.$refs.timeslot.open()
      this.show = false
      // this.showStartPicker = true
    },

    // 打开结束时间选择器
    openEndTimePicker() {
      this.show = false
      this.showEndPicker = true
    },

    // 开始时间确认
    onStartTimeConfirm(e) {
      this.startTimeStamp = e.value
      this.startTime = dayjs(e.value).format("YYYY-MM-DD HH:mm")
      // 如果开始时间大于结束时间，自动调整结束时间
      if (dayjs(this.startTime).isAfter(dayjs(this.endTime))) {
        uni.showToast({
          title: "开始时间不能大于结束时间",
          icon: "none",
        })
        return
      }
      this.showStartPicker = false
      this.show = true
      this.liveUrl = ""
      // 重新获取视频
      // this.fetchUserPlay()
    },

    // 结束时间确认
    onEndTimeConfirm(e) {
      this.endTimeStamp = e.value
      this.endTime = dayjs(e.value).format("YYYY-MM-DD HH:mm")
      // 如果结束时间小于开始时间，自动调整开始时间
      if (dayjs(this.endTime).isBefore(dayjs(this.startTime))) {
        uni.showToast({
          title: "结束时间不能小于开始时间",
          icon: "none",
        })
        return
      }
      this.showEndPicker = false
      this.show = true
      this.liveUrl = ""
      // 重新获取视频
      // this.fetchUserPlay()
    },
    close() {
      this.show = false
    },
    changeDate(e) {
      console.log("e :>> ", e)
      const { fulldate } = e
      this.dateCheckedValue = fulldate
    },
    confirmDate() {
      this.show = false
      this.date = this.dateCheckedValue
      this.startTime = this.startTimeCheckedValue
      this.endTime = this.endTimeCheckedValue

      this.fetchUserPlay()
    },
    openTimeSlot() {
      this.$refs.timeslot.open()
      this.show = false
    },
    confirmTime(e) {
      console.log("e :>> ", e)
      const { start, end } = e
      this.startTimeCheckedValue = start.hour + ":" + start.min
      this.endTimeCheckedValue = end.hour + ":" + end.min
      this.$refs.timeslot.close()
      this.show = true
    },
  },
  onLoad(options) {
    // 从路由参数获取设备信息
    if (options.deviceName) {
      this.deviceName = options.deviceName
    }
    if (options.deviceCode) {
      this.deviceCode = options.deviceCode
    }

    this.channelId = options.channelId
    this.deviceId = options.deviceId
    // this.fetchUserPlay()
    // this.getChannelInfo()
  },
  onShow() {},
  onUnload() {
    // 清除定时器
    if (this.timer) {
      clearInterval(this.timer)
    }
    if (this.directionTimer) {
      clearInterval(this.directionTimer)
    }
    if (this.zoomTimer) {
      clearInterval(this.zoomTimer)
    }
    if (this.apertureTimer) {
      clearInterval(this.apertureTimer)
    }
  },
  created() {},
}
</script>

<style lang="less" scoped>
.video-preview-container {
  width: 100%;
  min-height: 100vh;
  background: #f5f5f5;
}

// 设备名称栏
.device-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 80rpx;
  // background: linear-gradient(135deg, #7b68ee 0%, #9370db 100%);
  background-color: #2563e1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
  z-index: 999;

  .device-label {
    font-size: 32rpx;
    color: #fff;
    font-weight: bold;
  }

  .device-label-right {
    font-size: 28rpx;
    color: #fff;
  }
}

// 视频播放区域
.video-section {
  position: relative;
  width: 100%;
  height: 450rpx;
  background: #000;
  margin-top: 80rpx; // 88 + 80
}

.video-player {
  width: 100%;
  height: 100%;
  position: relative;
}

// 视频叠加层
.video-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
}

// 加载状态
.loading-status {
  position: absolute;
  top: 20rpx;
  left: 20rpx;
  display: flex;
  align-items: center;
  background: rgba(0, 0, 0, 0.6);
  padding: 10rpx 20rpx;
  border-radius: 30rpx;

  .loading-icon {
    width: 30rpx;
    height: 30rpx;
    margin-right: 10rpx;

    .loading-dot {
      display: block;
      width: 12rpx;
      height: 12rpx;
      background: #ff4d4f;
      border-radius: 50%;
      animation: blink 1s infinite;
    }
  }

  .loading-text {
    font-size: 24rpx;
    color: #fff;
  }
}

@keyframes blink {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0.3;
  }
}
.time_top_box {
  width: 100%;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1rpx solid #f0f0f0;
  .time_close,
  .time_comfirm {
    width: 100rpx;
    color: #999999;
    font-size: 28rpx;
    font-weight: 400;
    text-align: center;
  }
  .time_comfirm {
    color: #2563e1;
  }
  .time_text {
    flex: 1;
    font-size: 30rpx;
    font-weight: 800;
    text-align: center;
  }
}
// 视频信息（底部左侧）
.video-info-bottom {
  position: absolute;
  bottom: 20rpx;
  left: 20rpx;
  display: flex;
  flex-direction: column;
  color: #fff;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.8);

  .video-time {
    font-size: 28rpx;
    margin-bottom: 5rpx;
  }

  .video-device {
    font-size: 24rpx;
  }
}

// 设备名称（底部右侧）
.video-name-right {
  position: absolute;
  bottom: 20rpx;
  right: 20rpx;
  color: #fff;
  font-size: 28rpx;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.8);
}

// 中心图标
.center-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  pointer-events: all;

  .play-icon {
    font-size: 60rpx;
    color: #fff;
  }
}

// 功能按钮区域
.function-buttons {
  display: flex;
  justify-content: space-around;
  background: #fff;
  padding: 30rpx 20rpx;
  margin-bottom: 20rpx;
}

// 回放时间选择区域
.time-select-section {
  background: #fff;
  margin: 0 20rpx 20rpx;
  border-radius: 20rpx;
  padding: 0 30rpx;
  overflow: hidden;
  margin-top: 40rpx;
}

.time-select-item {
  display: flex;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  position: relative;

  &:last-child {
    border-bottom: none;
  }

  .time-label {
    font-size: 28rpx;
    color: #666;
    width: 140rpx;
  }

  .time-value-wrapper {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }

  .time-value {
    flex: 1;
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
    text-align: right;
  }

  .time-arrow {
    font-size: 32rpx;
    color: #999;
    margin-left: 20rpx;
  }
}

.function-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;

  .btn-icon {
    width: 80rpx;
    height: 80rpx;
    background: #f5f5f5;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 40rpx;
    margin-bottom: 10rpx;
  }

  .btn-label {
    font-size: 24rpx;
    color: #666;
  }
  .btn-icon-img {
    width: 50rpx;
    height: 50rpx;
    margin-bottom: 10rpx;
  }
}

// 控制区域
.control-section {
  background: #fff;
  margin: 0 20rpx 20rpx;
  border-radius: 20rpx;
  padding: 30rpx;
}

.section-header {
  margin-bottom: 30rpx;

  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
}

.control-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.control-card {
  background: #f8f8f8;
  border-radius: 16rpx;
  padding: 40rpx 30rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 180rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

  .card-icon {
    font-size: 60rpx;
    margin-bottom: 15rpx;
  }

  .card-label {
    font-size: 28rpx;
    color: #666;
    font-weight: 500;
  }
  .card-icon-img {
    width: 60rpx;
    height: 60rpx;
    margin-bottom: 15rpx;
  }
}

// 其他功能区域
.other-section {
  background: #fff;
  margin: 0 20rpx 20rpx;
  border-radius: 20rpx;
  padding: 30rpx;
}

.section-desc {
  margin-bottom: 20rpx;

  .desc-text {
    font-size: 26rpx;
    color: #999;
  }
}

.function-list {
  .function-item {
    display: flex;
    align-items: center;
    padding: 20rpx 0;

    .item-dot {
      font-size: 32rpx;
      color: #333;
      margin-right: 15rpx;
    }

    .item-text {
      font-size: 28rpx;
      color: #333;
    }
  }
}

// 云台控制面板样式
.gimbal-panel {
  position: relative;
}

// 右上角关闭按钮样式
.close-btn-top {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #666;
  z-index: 10;
}

// 方向控制样式
.direction-control {
  .direction-title {
    font-size: 28rpx;
    color: #333;
    text-align: center;
    margin-bottom: 40rpx;
  }

  .direction-pad {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    grid-template-rows: 1fr 1fr 1fr;
    gap: 8rpx;
    width: 320rpx;
    height: 320rpx;
    margin: 0 auto;
  }

  .direction-row {
    display: contents;
  }

  .direction-btn {
    width: 100rpx;
    height: 100rpx;
    border-radius: 20rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    font-weight: bold;
    color: #fff;
    box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.2);
    transition: all 0.2s ease;

    &:active {
      transform: scale(0.95);
    }

    &.up-btn {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      grid-column: 2;
      grid-row: 1;
    }

    &.down-btn {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      grid-column: 2;
      grid-row: 3;
    }

    &.left-btn {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      grid-column: 1;
      grid-row: 2;
    }

    &.right-btn {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      grid-column: 3;
      grid-row: 2;
    }
  }

  .direction-text {
    font-size: 28rpx;
    color: #fff;
    font-weight: bold;
  }
}

.control-group {
  margin-bottom: 40rpx;

  &:last-child {
    margin-bottom: 0;
  }

  .group-title {
    font-size: 28rpx;
    color: #333;
    text-align: center;
    margin-bottom: 20rpx;
    font-weight: bold;
  }

  .group-buttons {
    display: flex;
    gap: 30rpx;
  }

  .group-btn {
    flex: 1;
    height: 80rpx;
    border-radius: 16rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24rpx;
    font-weight: bold;
    color: #fff;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
    transition: all 0.2s ease;

    &:active {
      transform: scale(0.95);
    }

    // 变焦按钮
    &.zoom-in-btn {
      background: linear-gradient(135deg, #4caf50 0%, #66bb6a 100%);
    }

    &.zoom-out-btn {
      background: linear-gradient(135deg, #ff9800 0%, #ffb74d 100%);
    }

    // 光圈按钮
    &.aperture-open-btn {
      background: linear-gradient(135deg, #9c27b0 0%, #ba68c8 100%);
    }

    &.aperture-close-btn {
      background: linear-gradient(135deg, #e91e63 0%, #f48fb1 100%);
    }
  }

  .btn-text {
    font-size: 24rpx;
    color: #fff;
    font-weight: bold;
  }
}
</style>
